package org.jeecg.modules.websocket.manager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author by sean
 * @desc:
 * @since 2024-10-16 星期三 11:29:11
 */
@Slf4j
public class WebSocketSessionManager {

    /**
     * 保存连接 session 的地方
     */
    private static ConcurrentHashMap<String, WebSocketSessionGroup> SESSIONS_POOL = new ConcurrentHashMap<>();

    /**
     * 分组添加key
     * @param groupName
     * @param key
     * @param session
     */
    public static void addSession(String groupName, String key, WebSocketSession session) {
        SESSIONS_POOL.computeIfAbsent(groupName, k -> new WebSocketSessionGroup()).addSession(key, session);
    }

    public static WebSocketSessionGroup get(String groupName) {
        return SESSIONS_POOL.get(groupName);
    }

    public static WebSocketSession getSession(String groupName, String key) {
        WebSocketSessionGroup group = SESSIONS_POOL.get(groupName);
        if (group != null) {
            return group.getSession(key);
        }
        return null;
    }

    public static WebSocketSession removeSession(String groupName, String key) {
        WebSocketSessionGroup group = SESSIONS_POOL.get(groupName);
        if (group != null) {
            WebSocketSession socketSession = group.removeSession(key);
            if (group.isEmpty()) {
                SESSIONS_POOL.remove(groupName);
            }
            return socketSession;
        }
        return null;
    }

    /**
     * 删除并同步关闭连接
     * @param key
     */
    public static void removeAndClose(String groupName, String key) {
        WebSocketSession session = removeSession(groupName, key);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                // todo: 关闭出现异常处理
                e.printStackTrace();
            }
        }
    }

}
